import 'dart:convert';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_electroncheckrecord_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_electroncheckrecord.dart';
import 'package:flutter_admin/pages/odoo/product_electroncheckrecord/product_electroncheckrecord_edit.dart';
import 'package:flutter_admin/pages/odoo/product_electroncheckrecord/product_electroncheckrecord_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class ProductElectroncheckrecordList extends StatefulWidget {
  ProductElectroncheckrecordList({Key? key}) : super(key: key);

  @override
  _ProductElectroncheckrecordListState createState() =>
      _ProductElectroncheckrecordListState();
}

class _ProductElectroncheckrecordListState
    extends State<ProductElectroncheckrecordList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ProductElectroncheckrecord productElectroncheckrecord =
      ProductElectroncheckrecord();
  List<ProductElectroncheckrecord> selectedList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];
  //设备工位
  List<SelectOptionVO> stationIdList = [];

  List<SelectOptionVO> stateList = [];

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  DateFormat format = DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    productElectroncheckrecord.checkdateStart = Utils.getDate();
    productElectroncheckrecord.checkdateEnd = Utils.getDate();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopIdList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      stationIdList = await DynamicDataApi.getModelSelect(
          model: "base.productionstation",
          name: "stationname",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!));
      productElectroncheckrecord.workshopId = userInfo.deptId;
    }

    stateList = [
      SelectOptionVO(label: '', value: ''),
      SelectOptionVO(label: '提交', value: '0'),
      SelectOptionVO(label: '处理', value: '1'),
    ];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '检查开始时间',
            value: productElectroncheckrecord.checkdateStart,
            lastDate: isNotBlank(productElectroncheckrecord.checkdateEnd)
                ? format.parse(productElectroncheckrecord.checkdateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productElectroncheckrecord.checkdateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              productElectroncheckrecord.checkdateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '检查结束时间',
            value: productElectroncheckrecord.checkdateEnd,
            firstDate: isNotBlank(productElectroncheckrecord.checkdateStart)
                ? format.parse(productElectroncheckrecord.checkdateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productElectroncheckrecord.checkdateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              productElectroncheckrecord.checkdateEnd = v;
            },
          ),
          userInfo.major != null
              ? CrySelect(
                  label: '车间名称',
                  width: 280,
                  dataList: workshopIdList,
                  value: productElectroncheckrecord.workshopId,
                  onSaved: (v) => {productElectroncheckrecord.workshopId = v},
                  onChange: (v) async {
                    if (productElectroncheckrecord.workshopId != v) {
                      formKey.currentState!.save();
                      productElectroncheckrecord.workshopId = v;
                      productElectroncheckrecord.stationId = null;
                      try {
                        stationIdList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "base.productionstation",
                            name: "stationname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        stationIdList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            label: '设备工位',
            width: 280,
            dataList: stationIdList,
            value: productElectroncheckrecord.stationId,
            onSaved: (v) => {productElectroncheckrecord.stationId = v},
          ),
          CrySelect(
            width: 200,
            label: '状态',
            dataList: stateList,
            value: productElectroncheckrecord.status,
            onSaved: (v) {
              productElectroncheckrecord.status = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('状态'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('工厂名称'),
          //  onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('车间名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('设备工位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('问题类别'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('上传图片'),
          //   onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('检查日期'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('问题描述'),
          //   onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('原因分析'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('整改措施'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),

        DataColumn(
          label: Text('有效验证'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),

        DataColumn(
          label: Text('处理人'),
          //   onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('处理时间'),
          //  onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        ProductElectroncheckrecord productElectroncheckrecord =
            ProductElectroncheckrecord.fromMap(m);
        return [
          //isDisplayDesktop(context)?DataCell(
          //  CryButtonBar(
          //    children: [
          //      CryButton(
          //          iconData: Icons.edit,
          //          tip: S.of(context).modify,
          //          onPressed: () => _edit(productElectroncheckrecord)),
          //    ],
          //  ),
          // ):DataCell(Container()),
          DataCell(
              Text(productElectroncheckrecord.status == '0' ? '提交' : '处理')),
          DataCell(Text(productElectroncheckrecord.factoryName ?? '--')),
          DataCell(Text(productElectroncheckrecord.workshopName ?? '--')),
          DataCell(Text(productElectroncheckrecord.stationName ?? '--')),
          DataCell(Text(productElectroncheckrecord.questiontypeName ?? '--')),
          DataCell(productElectroncheckrecord.uploadimg == null
              ? Text(productElectroncheckrecord.uploadimg ?? '--')
              : Image.memory(
                  base64Decode(productElectroncheckrecord.uploadimg!),
                  width: 80,
                  height: 80,
                )),
          DataCell(
              Text(Utils.getDate(date: productElectroncheckrecord.checkdate))),
          DataCell(
              Text(productElectroncheckrecord.questiondescription ?? '--')),
          DataCell(Text(productElectroncheckrecord.causeanalysis ?? '--')),
          DataCell(
              Text(productElectroncheckrecord.rectificationmeasures ?? '--')),
          DataCell(
              Text(productElectroncheckrecord.effectiveverification ?? '--')),

          DataCell(Text(productElectroncheckrecord.handleuserId ?? '--')),
          DataCell(Text(productElectroncheckrecord.handledatetime ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null, false)),
        CryButtons.edit(
            context,
            selectedList.length == 1 && selectedList[0].status == '0'
                ? () => _edit(selectedList[0], false)
                : null),
        CryButtons.delete(
            context,
            selectedList.length != 0 && selectedList[0].status == '0'
                ? () => _delete(selectedList)
                : null),
        CryButton(
            label: '处理',
            iconData: Icons.beenhere,
            onPressed: selectedList.length == 1 && selectedList[0].status == '0'
                ? () => _edit(selectedList[0], true)
                : null),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

//isooa：false：处理，true ：修改
  _edit(ProductElectroncheckrecord? productElectroncheckrecord,
      bool isooa) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductElectroncheckrecordEdit(
          productElectroncheckrecord: productElectroncheckrecord,
          isooa: isooa,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(productElectroncheckrecord == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    productElectroncheckrecord = ProductElectroncheckrecord();
    formKey.currentState!.reset();
    if (userInfo.major != null) {
      stationIdList = [];
    }
    productElectroncheckrecord.checkdateStart = Utils.getDate();
    productElectroncheckrecord.checkdateEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await ProductElectroncheckrecordOdooApi.page(data: {
      "page": page,
      "domainList": productElectroncheckrecord.toDomainList()
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    } else {
      CryUtils.message(responseBodyApi.message.toString());
    }
  }

  _delete(List<ProductElectroncheckrecord> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await ProductElectroncheckrecordOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  // _sort(column, {ascending}) {
  //   page.orders[0].column = column;
  //   page.orders[0].asc = ascending ?? !page.orders[0].asc!;
  //   _query();
  // }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductElectroncheckrecordDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productElectroncheckrecord = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductElectroncheckrecord>(
                (e) => ProductElectroncheckrecord.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null, false);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0], false);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete, (context) async {
            _delete(selectedList);
          });
        } else if (v == OperationType.handle) {
          _edit(selectedList[0], true);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0 && selectedList[0].status == '0',
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.beenhere),
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('处理'),
          ),
        ),
      ],
    );
  }
}
